package com.fanfutian.eventproject.controller;


import ch.qos.logback.core.util.TimeUtil;
import com.fanfutian.eventproject.pojo.Result;
import com.fanfutian.eventproject.pojo.User;
import com.fanfutian.eventproject.service.UserService;
import com.fanfutian.eventproject.utils.JwtUtil;
import com.fanfutian.eventproject.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Slf4j
@RestController
@Validated
@RequestMapping("/user")
public class UserController {


    @Autowired
    private UserService userService;


    @Autowired
    private StringRedisTemplate redisTemplate;



    /**
     * 注册信息
     * @param username 用户名
     * @param password 密码
     * @return
     */
    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password){
        log.info("注册用户信息·····");
        // 查询是否有相同的用户名
        User user = userService.findUserByUsername(username);
        if(user != null){
            log.info("用户名已存在········");
            return Result.error("用户名已存在");
        }
        log.info("用户名不存在，添加用户········");
        userService.register(username, password);
        return Result.success();
    }


    /**
     * 登录
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/login")
    public Result login(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password){
        log.info("用户登录········");
        User user = userService.findUserByUsername(username);
        if(user == null){
            log.info("用户不存在········");
            return Result.error("用户不存在");
        }
        if(user.getPassword().equals(DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8)))){
            log.info("登录成功········");
            // 生成token
            Map<String, Object> claims = new HashMap<>();
            claims.put("username", user.getUsername());
            claims.put("id", user.getId());
            String token = JwtUtil.genToken(claims);
            log.info("生成的token: {}", token);
            // 把token存储到redis中,并设置过期时间(1小时)
            redisTemplate.opsForValue().set(token,token,1, TimeUnit.HOURS);
            return Result.success(token);
        }
        log.info("密码错误········");
        return Result.error("密码错误");
    }


    /**
     * 获取用户信息
     * @return
     */
//    @GetMapping("userInfo")
//    public Result<User> getUserInfo(@RequestHeader(name = "Authorization") String token){
//        log.info("获取用户信息········");
//        Map<String, Object> claims = JwtUtil.parseToken(token);
//        String username = (String)claims.get("username");
//        User user = userService.findUserByUsername(username);
//        log.info("用户信息: {}", user);
//        return Result.success(user);
//    }
    @GetMapping("userInfo")
    public Result<User> getUserInfo(){
        log.info("从token中获取用户信息········");
        // 从ThreadLocal中获取用户信息
        Map<String, Object> map = ThreadLocalUtil.get();
        // 获取用户名
        String username = map.get("username").toString();
        User user = userService.findUserByUsername(username);
        log.info("用户信息: {}", user);
        return Result.success(user);
    }


    /**
     * 更新用户信息
     * @param user
     * @return
     */
    @PutMapping("update")
    public Result updateUserInfo(@RequestBody @Validated User user){
        log.info("更新用户信息········");
        userService.updateUserInfo(user);
        return Result.success();
    }


    /**
     * 更新用户头像
     * @param avatarUrl
     * @return
     */
    @PatchMapping("updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl){
        log.info("更新用户头像········URL：{}", avatarUrl);
        userService.updateUserAvatar(avatarUrl);
        return Result.success();
    }

    /**
     * 更新用户密码
     * @param pwd
     * @return
     */
    @PatchMapping("updatePwd")
    public Result updatePassWord(@RequestBody Map<String,String> pwd, @RequestHeader(name = "Authorization") String token){

        log.info("修改用户密码········");

        String oldPwd = pwd.get("old_pwd");
        String newPwd = pwd.get("new_pwd");
        String rePwd = pwd.get("re_pwd");

        // 判断内容是否为空
        if(!(StringUtils.hasLength(oldPwd) || StringUtils.hasLength(newPwd) || StringUtils.hasLength(rePwd))){
            log.info("存在空的参数········密码更新失败");
            return Result.error("参数不能为空");
        }

        // 从ThreadLocal中获取用户信息
        Map<String, Object> claim = ThreadLocalUtil.get();
        String username = claim.get("username").toString();
        Integer id = (Integer) claim.get("id");
        User user = userService.findUserByUsername(username);
        String oldMd5DigestAsHex = DigestUtils.md5DigestAsHex(oldPwd.getBytes(StandardCharsets.UTF_8));
        // 判断密码,密码不同就返回错误信息
        if(!oldMd5DigestAsHex.equals(user.getPassword())){
            log.info("原密码错误········密码更新失败");
            return Result.error("原密码错误");
        }

        // 判断新密码和确认密码是否一致
        if(!newPwd.equals(rePwd)){
            log.info("新密码和确认密码不一致········密码更新失败");
            return Result.error("新密码和确认密码不一致");
        }

        // 新密码进行加密
        String newMd5DigestAsHex = DigestUtils.md5DigestAsHex(newPwd.getBytes(StandardCharsets.UTF_8));
        userService.updateUserPwd(newMd5DigestAsHex,id);
        // 删除redis中的token
        redisTemplate.opsForValue().getOperations().delete(token);
        return Result.success();
    }

}
